package com.cao.springbootinit.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cao.springbootinit.annotation.ScoringStrategyConfig;
import com.cao.springbootinit.common.ErrorCode;
import com.cao.springbootinit.exception.BusinessException;
import com.cao.springbootinit.model.dto.question.QuestionContenDto;
import com.cao.springbootinit.model.entity.App;
import com.cao.springbootinit.model.entity.Question;
import com.cao.springbootinit.model.entity.ScoringResult;
import com.cao.springbootinit.model.entity.UserAnswer;
import com.cao.springbootinit.model.vo.QuestionVO;
import com.cao.springbootinit.service.QuestionService;
import com.cao.springbootinit.service.ScoringResultService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义测评应用评分
 */
@ScoringStrategyConfig(appType = 1, scoringStrategy = 0)
public class CustomTestScoringStrategy implements ScoringStrategy {
    @Resource
    private QuestionService questionService;
    @Resource
    private ScoringResultService scoringResultService;

    @Override
    public UserAnswer calculate(List<String> choices, App app) throws Exception {
        Long appId = app.getId();
        if (appId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "应用id不能为空");
        }
        //1.根据id查询题目和题目结果信息
        Question question = questionService.getOne(
                Wrappers.lambdaQuery(Question.class).eq(Question::getAppId, appId)
        );
        List<ScoringResult> scoringResultList = scoringResultService.list(
                Wrappers.lambdaQuery(ScoringResult.class).eq(ScoringResult::getAppId, appId
                ));
        //2.统计用户每个选择对应属性个数，如I=10个 E=5个
        //便利题目列表
        Map<String, Integer> optionCunt = new HashMap<>();
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContenDto> questionContent = questionVO.getQuestionContent();
        for (QuestionContenDto questionContenDto : questionContent) {
            //便利答案列表
            for (String choice : choices) {
                //遍历题目中的选项
                for (QuestionContenDto.Optional optional : questionContenDto.getOptions()) {
                    //如果答案和题目key属性匹配
                    if (optional.getKey().equals(choice)) {
                        //获取选项中的result属性
                        String result = optional.getResult();

                        //如果result属性不在optionCunt中，初始化为0
                        if (!optionCunt.containsKey(result)) {
                            optionCunt.put(result, 0);
                        }
                        //将result属性对应的值加1
                        optionCunt.put(result, optionCunt.get(result) + 1);
                    }
                }
            }
        }
        //3.遍历每种评分结果，计算那个结果的得分更高
        int maxScore = 0;
        ScoringResult scoringResult = scoringResultList.get(0);
        for (ScoringResult result : scoringResultList) {
            //计算当前得分
            List<String> resultProp = JSONUtil.toList(result.getResultProp(), String.class);
            int sum = resultProp.stream()
                    .mapToInt(prop -> optionCunt.getOrDefault(prop, 0))
                    .sum();
            //如果 当前得分比最大得分高，更新最大得分和评分结果
            if (sum > maxScore) {

                maxScore = sum;
                scoringResult = result;
            }
        }
        //构造返回值，进行返回
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(scoringResult.getId());
        userAnswer.setResultName(scoringResult.getResultName());
        userAnswer.setResultDesc(scoringResult.getResultDesc());
        userAnswer.setResultPicture(scoringResult.getResultPicture());
        return userAnswer;
    }
}
